<template>

  <div class="gridContainer">
    <div v-for="(item,key) in cardItems"
         :key="key"
         @click="flipCard(key, item)" class="flip-container" :class="{flipped: item.isFlit}">
      <a-card class="front-side">
        <img :src="item.base64_content" style="height: 100%;width: 100%"/>
      </a-card>

      <a-card class="back-side">
        <div class="back-font">{{
            item.word
          }}</div>
      </a-card>
    </div>
  </div>


  <div class="controls">
    <a-button id="reset-btn" @click="resetCards" type="primary" :loading="isResetting">
      {{ isResetting ? '重置中...' : '重置卡片' }}
    </a-button>
  </div>


</template>

<script setup lang="ts">
import {ref, watch} from "vue";
import {invoke} from "@tauri-apps/api/core";
import {useRoute} from "vue-router";
import {ImgInfo} from "../model.ts";
import {ReciteWordItem} from "./ReciteWordItem.ts";

const route = useRoute()
let sub = route.query.sub
let baseDir = "/data/记单词/" + sub

// 监听整个路由对象变化
watch(
    () => route.fullPath,
    () => {
      console.log('路由变化了，新参数:', route.query)
      // 这里执行数据加载等操作
      baseDir = "/data/记单词/" + route.query.sub;
      getImgPaths()
    }
)

// 读取正面和背面的卡片
const getImgPaths = async function () {
  const imgInfos: ImgInfo[] = await invoke('load_img_base64', {"dir": baseDir, "randFlag": true});
  console.log("imgInfos=", imgInfos)
  const items: ReciteWordItem[] = imgInfos.map((img) => {
        // 卡片默认是未翻转的
        return {base64_content: img.base64_content, word: img.name, isFlit: false};
      }
  );

  cardItems.value = items;
  console.log("baseDir=", baseDir)
  console.log("cardItems=", cardItems.value)
}

getImgPaths();

let cardItems = ref<ReciteWordItem[]>([])

// 翻转卡片
let flipCard = function (index: any, item: ReciteWordItem) {
  console.log(index, item)
  item.isFlit = !item.isFlit;
}

// 新增：重置状态跟踪
const isResetting = ref(false)

// 修改后：
const resetCards = async function () {
  isResetting.value = true

  // 第一步：先重置所有卡片为背面
  cardItems.value.forEach(item => {
    item.isFlit = false
  })

  // 第二步：等待DOM更新确保卡片翻到背面
  await new Promise(resolve => setTimeout(resolve, 500))

  // 第三步：加载新图片
  try {
    await getImgPaths()
  } finally {
    isResetting.value = false
  }
}

</script>

<style scoped>

.back-font {
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 15vh;
  font-size: 200%;
  color: black;
  font-weight: bold;
}

</style>
